<?php
class Login extends CI_Controller 
{
	function __construct()
	{
		parent::__construct();
		$this->load->model('login_model');
	}
	
	function index()
	{
		redirect(((!check_auth()) ? "/login/auth" : site_url("/home")));
		$this->auth();
	}

	function auth()
	{
		if(check_auth()) redirect(site_url("/home"));
		$this->load->view("login");
	}
	
	function do_login()
	{
		//== Login Dummy Data Administrator
		if (isset($_POST['username']) && isset($_POST['password']))
		{      
		    //Edit by Andi Siswanto 29/10/2014  
		    $uname=$_POST['username'];
            $pass=$_POST['password'];  
		    $countLogin=$this->login_model->cek_dataLoginCount($uname,$pass);
            if($countLogin=='1'){
                $dataLogin=$this->login_model->cek_dataLogin($uname,$pass);
                foreach($dataLogin as $dt){
                    $username=$dt['USERNAME'];
                    $password=$dt['PASSWORD'];
                    $jobposition=$dt['JOB_POSITION'];
                    $vendorid=$dt['VENDOR_ID'];
                    $vendorsiteid=$dt['VENDOR_SITE_ID'];
                    $nik=$dt['ID'];
                    $name=$dt['NAME'];
                    $org=$dt['ORG'];
                    $job=$dt['JOB'];
                    $email=$dt['EMAIL'];
                    $msisdn=$dt['MSISDN'];
                }
                
                if(strtolower($username)=="administrator_fm" && md5($pass)==$password)
    			{
    				$logindata = array(
    						'expires_by'	=> time() + 1440, 
    						'LOG'			=> 1,
    						'HR_ID'			=> 999999, 
    						'USERNAME'		=> 'Administrator', 
    						'username'		=> $username, ///ada
    						'jobposition'	=> $jobposition, //ada
    						//'JOBPOSITION'	=> 'Administrator',
    						'vendorid'		=> $vendorid, //ada
    						'vendorsiteid'	=> $vendorsiteid, //ada
    						'nid'			=> 999999, 
    						'nik'			=> $id, //ada
    						'name'			=> $name, //ada
    						'group'			=> 'ADMIN',
    						'org'			=> $org, //ada
    						'gender'		=> 'M',
    						'job'			=> $job, //ada
    						//'JOB'			=> 'Administrator',
    						'org_id'		=> '',
    						'org'			=> 'Administrator',
    						'location'		=> 'Administrator',
    						'city'			=> 'Jakarta',
    						'email'			=> $email, //ada
    						'msisdn'		=> $msisdn, //ada
    						'directorate'	=> '',
    						'subdir'		=> '',
    						'active_flag'	=> '', 
    						'trip_permit'	=> '',
    						'loginfrom'		=> 'FM',
    						'LEVEL'			=> 'ADMIN',
                            
                            'ROLE_CODE'     =>'', 
                            'ACTIVECODE'    =>'',    
                            'SRQ_APPROVAL_ROLE' =>''                                                                                                    
    				);
                    
                    //var_dump($logindata); exit;
    				$this->session->set_userdata('login',$logindata);
    				
    				redirect(site_url("/home"));
    			}
    			else //cari cara untuk login sebagai user, gantikan script di bawah ini
    			{
    				$Error = array('Error' => validation_errors());
    				$this->session->set_userdata($Error);
    				redirect('/login/auth');
    			}
            }
            else{
                $Error = array('Error' => validation_errors());
    			$this->session->set_userdata($Error);
    			redirect('/login/auth');
            }  	
            //var_dump($password); exit;	  
			//if(strtolower($_POST['username']) == "admin" && $_POST['password'] == "111") //GANTI
            
			
			/*
				// Set session values here
				$_SESSION['expires_by']	 = time() + 1440 ;
				$_SESSION['LOG']         = 1;
				$_SESSION['HR_ID']       = $hrid ;
				$_SESSION['USERNAME']    = $username;	
				$_SESSION['username'] 	 = $username;
				$_SESSION['vendorid'] 	 = $vendorid;
				$_SESSION['vendorsiteid']= $vendorsiteid;
				$_SESSION['nid'] 	 = $nid;
				$_SESSION['nik']         = $nik;
				$_SESSION['name'] 	 = $name;
				$_SESSION['group'] 	 = $group;
				$_SESSION['gender'] 	 = $gender;
				$_SESSION['job'] 	 = $job;
				$_SESSION['jobposition'] = $jobposition;
				$_SESSION['JOB'] 	 = $job;
				$_SESSION['JOBPOSITION'] = $jobposition;
				$_SESSION['org_id'] 	 = $org_id;
				$_SESSION['org'] 	 = $org;
				$_SESSION['location'] 	 = $location;
				$_SESSION['city'] 	 = $city;
				$_SESSION['email'] 	 = $email;
				$_SESSION['msisdn'] 	 = $msisdn;
				$_SESSION['directorate'] = $directorate;
				$_SESSION['subdir'] 	 = $subdir;
				$_SESSION['active_flag'] = $active_flag;
				$_SESSION['trip_permit'] = $trip_permit;
				$_SESSION['loginfrom']   = 'FM';
				$_SESSION['HR_ID'] 	 = $HR_ID;
				$_SESSION['LEVEL']	 = $LEVEL;
			*/
		}
		else
		{
			$Error = array('Error' => validation_errors());
			$this->session->set_userdata($Error);
			redirect('/login/auth');
		}
		
		
		$this->form_validation->set_rules('username', 'User Name', 'trim|required');
		$this->form_validation->set_rules('password', 'Password', 'trim|required|callback_CheckDb');
		if($this->form_validation->run() == FALSE)
		{ 
			$Error = array('Error' => validation_errors());
			$this->session->set_userdata($Error);
			redirect('/login/auth');
		}
		else
		{
			redirect(site_url("/home"));
		}		
	}
		
	function do_reset()
	{
		if($_POST)
		{
			$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email');
			if($this->form_validation->run() !== FALSE)
			{
				/*$email = $this->input->post('email');
				$message = 'Dear $user_fullname,<br/><br/><br/>You request new password<br/>User : asyik Pass :$new_password';
				$this->load->library('email');
				$this->email->from('ery.yoga@gmail.com');
				$this->email->to($email);p
				$this->email->subject('Password Recovery');
				$this->email->message($message);			
				$this->email->send();*/
				$Success = array('Success' => 'Email successfully sent !. Check Your Email');
				redirect('login/auth');
				//$this->output->set_content_type('json');
				//$this->output->set_status_header('200');	
				//$this->output->set_content_type('application/json');
 				//$this->output->set_output(json_encode($success));
			}
			else
			{
				$Error = array('Error' => 'Email was not send !');
				$this->session->set_userdata($Error);
				redirect('login/auth');
				//$this->output->set_content_type('json');
				//$this->output->set_status_header('422',$email_error);
				//redirect('auth/login');
				//$this->output->set_output(json_encode($email_error));
			}
		}	
		/*	$data['titleInfo'] = array('HeaderTitle' => 'Admin - Reset Password','Styles' => 'styles.css');
		$this->load->view('header',$data);
		$this->load->view('lostpassword');
		$this->load->view('footer');*/
	}
	
	function do_logout()
  	{
		// $user = explode('|',$this->encrypt->decode($_COOKIE[SITE_NAME]));
		// $this->db->update('AM_USERS',array('online' => 0,'lastlogin' => date("Y/m/d  H:i:s")),array('user_id' => $user[2]));
		// setcookie(SITE_NAME, "", time() - 3600, "/", '.telkomsel.net');
		// redirect('login/auth', 'refresh');
		
		$this->session->unset_userdata('login');
		redirect('/login', 'refresh');
	}

    function CheckDb($password)
  	{
		$login_name = $this->input->post('username');
		$checkUser = $this->login_model->checkUser($login_name);
		if($checkUser == TRUE)
		{
			$is_active = $this->login_model->checkUserActive($login_name);
			if($is_active)
			{
				$row = $this->login_model->do_login($login_name, $password);
				if(count($row) > 0)
				{
					$user_verified = array(
											//'sess_id' => $this->session->userdata('session_id'),
											'uid' => $row['USER_ID'],
											'logname' => $row['LOGIN_NAME'],
											'roleid' => $row['ROLE']
											);					
					//$this->session->set_userdata('uinfo',$user_verified);
					$cookie = $this->encrypt->encode($row['LOGIN_NAME']."|".md5($password)."|".$row['USER_ID'].'|'.time());
					//$this->db->update("AM_USERS",array("LAST_LOGIN" => date("m/d/Y")),array('USER_ID' =>$row['USER_ID']));
					//$sql = "UPDATE AM_USERS SET LAST_LOGIN = '".date("Y-m-d")."' WHERE USER_ID = ".$row['USER_ID'];
					//	 $this->db->query($sql);
					setcookie(SITE_NAME, $cookie, 0, "/", 'telkomsel.net');
					return TRUE;
				}
				else
				{ 
					$this->form_validation->set_message('CheckDb', 'Password Invalid !');
					return FALSE;
				}
			}
			else
			{
				$this->form_validation->set_message('CheckDb', 'Your account no longer Active !');
				return FALSE;
			}
		}
		else 
		{ 
			$this->form_validation->set_message('CheckDb', 'Username invalid !');
			return FALSE;
    	}
	}
}
?>